/**
 * LoginActivity.java $version 1.0 Aug 12, 2012
 *
 * Copyright 2011 Pravin Kumar Corp. All rights Reserved.
 * Pravin Kumar PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.sales.service.view;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;


import com.sales.service.R;
import com.sales.service.constants.ServiceConstants;
import com.sales.service.utils.CacheManager;
import com.sforce.android.soap.partner.BaseResponseListener;
import com.sforce.android.soap.partner.OAuthConnectorConfig;
import com.sforce.android.soap.partner.OAuthLoginResult;
import com.sforce.android.soap.partner.Salesforce;
import com.sforce.android.soap.partner.fault.ApiFault;
import com.sforce.android.soap.partner.fault.ExceptionCode;

/**
 * Provide a brief description of LoginActivity.
 * Specify the following items:
 *  - What does it do.
 *  - Its dependencies.
 *  - What section / item in the class document does it correspond to.
 *
 * @author Accenture India
 */
public class LoginActivity extends Activity{
	
	private static final String TagProject = "SalesService";
	private static final String TagPage = "Login ::";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Salesforce.init(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		String consumerKey = getResources().getString(R.string.consumerKey);
		String callbackUrl = getResources().getString(R.string.callbackUrl);

		OAuthConnectorConfig parameters = new OAuthConnectorConfig(consumerKey, callbackUrl);

		Salesforce.loginOAuth(this, parameters, new BaseResponseListener() {

			@Override
			public void onSforceError(ApiFault apiFault) {
				String msg = apiFault.getExceptionMessage();
				String code = apiFault.getExceptionCode().getValue();
				if(code.equals(ExceptionCode._ACCESS_DENIED)){
					Log.i(LoginActivity.TagProject, "User didn't grant access");
				}
				
				Log.i(LoginActivity.TagProject, "Exception = " + msg);
			}

			@Override
			public void onException(Exception arg0) {

			}

			@Override
			public void onComplete(Object sObjects) {
				OAuthLoginResult result = (OAuthLoginResult) sObjects;

				CacheManager.getInstance().addProperty(ServiceConstants.CACHE_OAUTH_KEY, result);

				Intent intent = new Intent(LoginActivity.this, MainPageActivity.class);
				LoginActivity.this.startActivity(intent);
			}
		});
	}

}
